package com.liujun.spring4.demo.aop.ioc.base.resource;

import jdk.internal.util.xml.impl.Input;
import org.springframework.core.io.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;

/**
 * 资源操作示例
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-11 07:11:00
 */
public class FileResourceExample {


  public static void main(String[] args) {

    try {
      String filePath =
          "D:\\java\\workspace\\idea\\git\\spring4-demo\\spring4demo-chapter4ioc\\src\\main\\resources\\conf\\file1.txt";

      // 使用系统文件路径方式加载文件
      WritableResource res1 = new PathResource(filePath);

      // 使用类路径的方式加载文件
      Resource res2 = new ClassPathResource("conf/file1.txt");

      // 3，使用writableResource接口写资源文件
      OutputStream stream1 = res1.getOutputStream();
      stream1.write("欢迎光临\n小飞论坛".getBytes());
      stream1.close();

      // 4,使用Resource接口读资源文件
      InputStream ins1 = res1.getInputStream();
      InputStream ins2 = res2.getInputStream();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int i;
      while ((i = ins1.read()) != -1) {
        baos.write(i);
      }
      System.out.println(baos.toString());

      System.out.println("res1:" + res1.getFilename());
      System.out.println("res2:" + res2.getFilename());

      //在相对路径上创建新的文件
      Resource resource2 =  res1.createRelative("test1.txt");
      System.out.println(resource2);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
